﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ERPWinFormWork.Test.Test.Dtos;
using ERPWinFormWork.Test.Test.Dtos.Write;
using ERPWinFormWork.Test.TestCode;

namespace ERPWinFormWork.Test
{
    public partial class AddInInspection : Form
    {
        private ApiClient _apiClient;
        private int? _selectedMaterialId;
        private int? _selectedPurchaseId;
        private Action _onSuccessCallback; // 添加成功后的回调函数

        public AddInInspection(Action onSuccessCallback = null)
        {
            _onSuccessCallback = onSuccessCallback;
            InitializeComponent();
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);

            // 统一UI美化
            ApplyUiPolish();

            // 根据时间自动生成检验编号（时间戳）
            textIninspectionNode.Text = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            // 初始化日期控件
            InitializeDateControls();

            // 配置检测项目表格
            ConfigureTestingItemsGrid();

            // 绑定表格事件
            this.dgvIntesting_ItemsId.CellContentClick += dgvtesting_ItemsId_CellContentClick;
            this.dgvIntesting_ItemsId.DataBindingComplete += Dgvtesting_ItemsId_DataBindingComplete;

            // 绑定物料选择按钮事件
            this.btnInMater.Click += btnInMater_Click;

            // 绑定“新增检测项”按钮事件
            this.btnaddIninspe.Click += btnaddIninspe_Click;


            // 添加数量变化事件监听器
            AddCalculationEventListeners();

            // 初始化默认值
            InitializeDefaultValues();

            // 加载下拉框数据
            LoadDropdownData();

            // 验证控件
            ValidateControls();
        }

        private void ApplyUiPolish()
        {
            try
            {
                // 全局字体与背景
                this.Font = new Font("微软雅黑", 10.5F, FontStyle.Regular, GraphicsUnit.Point, 134);
                this.BackColor = Color.FromArgb(248, 250, 252);

                // 标签统一前景色
                var dark = Color.FromArgb(64, 64, 64);
                foreach (Control c in this.Controls)
                {
                    if (c is CCWin.SkinControl.SkinLabel lbl)
                    {
                        lbl.ForeColor = dark;
                    }
                }

                // 按钮大小微调（防止主题覆盖导致大小回退）
                if (btnAddIn != null) btnAddIn.Size = new Size(90, 40);
                if (btnCloseIn != null) btnCloseIn.Size = new Size(90, 40);
                if (btnaddIninspe != null) btnaddIninspe.Size = new Size(110, 38);
                if (btnInMater != null) btnInMater.Size = new Size(60, 30);

                // 日期控件：水印与尺寸
                if (dateInshipment_Date != null)
                {
                    if (dateInshipment_Date.Size.Height < 32)
                        dateInshipment_Date.Size = new Size(dateInshipment_Date.Width, 32);
                }
                if (dateIninspection_Date != null)
                {
                    if (dateIninspection_Date.Size.Height < 32)
                        dateIninspection_Date.Size = new Size(dateIninspection_Date.Width, 32);
                }

                // 下拉框水印
                if (cboaddIndepartment_Id != null)
                {
                    cboaddIndepartment_Id.WaterText = "请选择检验部门";
                    if (cboaddIndepartment_Id.Height < 32)
                        cboaddIndepartment_Id.Size = new Size(cboaddIndepartment_Id.Width, 32);
                }

                // 表格美化
                if (dgvIntesting_ItemsId != null)
                {
                    dgvIntesting_ItemsId.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                    dgvIntesting_ItemsId.EnableHeadersVisualStyles = false;
                    dgvIntesting_ItemsId.ColumnHeadersHeight = 40;
                    dgvIntesting_ItemsId.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
                    dgvIntesting_ItemsId.RowTemplate.Height = 28;
                    dgvIntesting_ItemsId.GridColor = Color.FromArgb(224, 224, 224);

                    dgvIntesting_ItemsId.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(41, 128, 185);
                    dgvIntesting_ItemsId.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
                    dgvIntesting_ItemsId.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    dgvIntesting_ItemsId.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 10F, FontStyle.Bold);

                    dgvIntesting_ItemsId.DefaultCellStyle.Font = new Font("微软雅黑", 9F);
                    dgvIntesting_ItemsId.DefaultCellStyle.SelectionBackColor = Color.FromArgb(59, 188, 240);
                    dgvIntesting_ItemsId.DefaultCellStyle.SelectionForeColor = Color.White;

                    // 双缓冲，减少滚动/刷新闪烁
                    var pi = typeof(DataGridView).GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                    pi?.SetValue(dgvIntesting_ItemsId, true, null);
                }

                // 文本框水印（如控件支持）
                if (textIninspectionNode != null)
                {
                    textIninspectionNode.WaterText = "请输入检验单编号";
                    textIninspectionNode.SkinTxt.WaterText = "请输入检验单编号";
                }
                if (textIninspectionName != null)
                {
                    textIninspectionName.WaterText = "请输入检验单名称";
                    textIninspectionName.SkinTxt.WaterText = "请输入检验单名称";
                }
                if (textInmatername != null)
                {
                    textInmatername.WaterText = "请输入物料名称";
                    textInmatername.SkinTxt.WaterText = "请输入物料名称";
                }
                if (textInmatercode != null)
                {
                    textInmatercode.WaterText = "请输入物料编号";
                    textInmatercode.SkinTxt.WaterText = "请输入物料编号";
                }
                if (textInmaterxh != null)
                {
                    textInmaterxh.WaterText = "请输入规格型号";
                    textInmaterxh.SkinTxt.WaterText = "请输入规格型号";
                }
                if (textInmaterunit != null)
                {
                    textInmaterunit.WaterText = "请输入单位";
                    textInmaterunit.SkinTxt.WaterText = "请输入单位";
                }
                if (textaddInbatch != null)
                {
                    textaddInbatch.WaterText = "请输入批次号";
                    textaddInbatch.SkinTxt.WaterText = "请输入批次号";
                }
            }
            catch { }
        }


        /// <summary>
        /// 新增检测项：打开检测项目选择窗体，回填到表格，并清空相关计算字段
        /// </summary>
        private void btnaddIninspe_Click(object sender, EventArgs e)
        {
            var dialog = new GetInspection(onSelected: items =>
            {
                if (items == null || items.Count == 0) return;

                // 确保网格配置完成（不会重复添加列）
                ConfigureTestingItemsGrid();

                if (dgvIntesting_ItemsId.DataSource is BindingList<Testing_ItemsDtos> binding)
                {
                    foreach (var it in items)
                    {
                        if (!binding.Any(x => x.Id == it.Id))
                        {
                            binding.Add(it);
                        }
                    }
                }
                else
                {
                    dgvIntesting_ItemsId.DataSource = new BindingList<Testing_ItemsDtos>(items);
                }

                // 添加检测项目后，清空相关字段，等待用户输入数量
                ClearCalculationResults();
                ClearAllDefectCounts();
            });

            dialog.Show(this);
        }

        /// <summary>
        /// 校验数量输入（检测数量、合格数量）
        /// </summary>
        private bool ValidateQuantityInputs()
        {
            if (!int.TryParse(textIninspection_Count?.Text, out var inspectionCount) || inspectionCount <= 0)
            {
                MessageBox.Show("请输入有效的检测数量（>0）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (!int.TryParse(textInqualified_Count?.Text, out var qualifiedCount) || qualifiedCount < 0)
            {
                MessageBox.Show("请输入有效的合格数量（>=0）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (qualifiedCount > inspectionCount)
            {
                MessageBox.Show("合格数量不能大于检测数量", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
        }




        /// <summary>
        /// 选择物料（弹出物料列表并回填）
        /// </summary>
        private void btnInMater_Click(object sender, EventArgs e)
        {
            var dialog = new PurchaseMaterialSelectForm(onSelected: material =>
            {
                if (material == null) return;

                // 反填物料信息
                if (textInmatername != null) textInmatername.Text = material.MaterialName ?? string.Empty;
                if (textInmatercode != null) textInmatercode.Text = material.MaterialNumber ?? string.Empty;
                if (textInmaterunit != null) textInmaterunit.Text = material.UnitName ?? string.Empty;
                if (textInmaterxh != null) textInmaterxh.Text = material.Specifications ?? string.Empty;

                // 保存选中关联ID，用于提交
                _selectedMaterialId = material.MaterialId;
                _selectedPurchaseId = material.Id;
            });

            dialog.Show(this);
        }






        /// <summary>
        /// 配置检测项目网格
        /// </summary>
        private void ConfigureTestingItemsGrid()
        {
            var grid = dgvIntesting_ItemsId;
            grid.AllowUserToAddRows = false;

            // 添加致命缺陷列
            if (!grid.Columns.Contains("colFatalCount"))
            {
                var colFatal = new DataGridViewTextBoxColumn
                {
                    Name = "colFatalCount",
                    HeaderText = "致命缺陷",
                    ValueType = typeof(int),
                    Width = 90
                };
                grid.Columns.Add(colFatal);
            }

            // 添加严重缺陷列
            if (!grid.Columns.Contains("colSeriousCount"))
            {
                var colSerious = new DataGridViewTextBoxColumn
                {
                    Name = "colSeriousCount",
                    HeaderText = "严重缺陷",
                    ValueType = typeof(int),
                    Width = 90
                };
                grid.Columns.Add(colSerious);
            }

            // 添加轻微缺陷列
            if (!grid.Columns.Contains("colMinorCount"))
            {
                var colMinor = new DataGridViewTextBoxColumn
                {
                    Name = "colMinorCount",
                    HeaderText = "轻微缺陷",
                    ValueType = typeof(int),
                    Width = 90
                };
                grid.Columns.Add(colMinor);
            }

            // 添加缺陷填报操作列
            if (!grid.Columns.Contains("colDefect"))
            {
                var defectCol = new DataGridViewButtonColumn
                {
                    Name = "colDefect",
                    HeaderText = "操作",
                    Text = "缺陷填报",
                    UseColumnTextForButtonValue = true,
                    Width = 90
                };
                grid.Columns.Add(defectCol);
            }

            // 添加删除列
            if (!grid.Columns.Contains("colDelete"))
            {
                var deleteCol = new DataGridViewButtonColumn
                {
                    Name = "colDelete",
                    HeaderText = string.Empty,
                    Text = "删除",
                    UseColumnTextForButtonValue = true,
                    Width = 70
                };
                grid.Columns.Add(deleteCol);
            }
        }

        /// <summary>
        /// 表格单元格点击事件
        /// </summary>
        private void dgvtesting_ItemsId_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            var grid = dgvIntesting_ItemsId;
            var name = grid.Columns[e.ColumnIndex].Name;

            if (name == "colDelete")
            {
                grid.Rows.RemoveAt(e.RowIndex);
                // 删除检测项目后，清空相关字段
                ClearCalculationResults();
                ClearAllDefectCounts();
                return;
            }

            if (name == "colDefect")
            {
                // 打开缺陷选择窗体，回填数量到当前行
                var currentRowIndex = e.RowIndex;
                var form = new DefectSelectForm((fatal, serious, minor) =>
                {
                    var row = dgvIntesting_ItemsId.Rows[currentRowIndex];
                    row.Cells["colFatalCount"].Value = fatal;
                    row.Cells["colSeriousCount"].Value = serious;
                    row.Cells["colMinorCount"].Value = minor;

                    // 触发重新计算
                    CalculateQuantitiesAndRates();
                });
                form.Show(this);
            }
        }

        /// <summary>
        /// 数据绑定完成事件
        /// </summary>
        private void Dgvtesting_ItemsId_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            var grid = dgvIntesting_ItemsId;
            grid.AllowUserToAddRows = false;

            // 设置列头中文显示
            if (grid.Columns.Contains("Items_Name")) grid.Columns["Items_Name"].HeaderText = "检测项目";
            if (grid.Columns.Contains("DetectionType_Name")) grid.Columns["DetectionType_Name"].HeaderText = "检验类型";
            if (grid.Columns.Contains("Tools_Name")) grid.Columns["Tools_Name"].HeaderText = "检验工具";

            // 把操作列放到最后
            int count = grid.Columns.Count;
            if (count <= 0) return;

            var orderTail = new List<string> { "colDelete", "colDefect", "colMinorCount", "colSeriousCount", "colFatalCount" };
            int current = count - 1;
            foreach (var name in orderTail)
            {
                if (grid.Columns.Contains(name))
                {
                    grid.Columns[name].DisplayIndex = current;
                    current--;
                }
            }

            // 列重新排序完成后，清空相关字段
            ClearCalculationResults();
            ClearAllDefectCounts();
        }

        /// <summary>
        /// 添加数量变化事件监听器
        /// </summary>
        private void AddCalculationEventListeners()
        {
            // 监听检测数量和合格数量的变化
            if (textIninspection_Count != null)
            {
                textIninspection_Count.TextChanged += (s, e) =>
                {
                    CalculateQuantitiesAndRates();
                };
            }

            if (textInqualified_Count != null)
            {
                textInqualified_Count.TextChanged += (s, e) =>
                {
                    CalculateQuantitiesAndRates();
                };
            }

            // 监听表格中缺陷数量的变化
            if (dgvIntesting_ItemsId != null)
            {
                dgvIntesting_ItemsId.CellValueChanged += (s, e) =>
                {
                    if (e.ColumnIndex >= 0 && dgvIntesting_ItemsId.Columns[e.ColumnIndex] != null)
                    {
                        string columnName = dgvIntesting_ItemsId.Columns[e.ColumnIndex].Name;
                        if (columnName == "colFatalCount" || columnName == "colSeriousCount" || columnName == "colMinorCount")
                        {
                            CalculateQuantitiesAndRates();
                        }
                    }
                };
            }
        }

        /// <summary>
        /// 自动计算不合格数量和缺陷率
        /// </summary>
        private void CalculateQuantitiesAndRates()
        {
            try
            {
                // 检查是否有检测项目
                if (dgvIntesting_ItemsId == null || dgvIntesting_ItemsId.Rows.Count == 0)
                {
                    ClearCalculationResults();
                    return;
                }

                // 检查控件是否存在
                if (textIninspection_Count == null || textInqualified_Count == null)
                {
                    return;
                }

                // 获取文本值并验证
                string inspectionCountText = textIninspection_Count.Text?.Trim();
                string qualifiedCountText = textInqualified_Count.Text?.Trim();

                if (string.IsNullOrEmpty(inspectionCountText) || string.IsNullOrEmpty(qualifiedCountText))
                {
                    ClearCalculationResults();
                    return;
                }

                // 解析检测数量和合格数量
                if (!int.TryParse(inspectionCountText, out int inspectionCount) || inspectionCount < 0)
                {
                    ClearCalculationResults();
                    return;
                }

                if (!int.TryParse(qualifiedCountText, out int qualifiedCount) || qualifiedCount < 0)
                {
                    ClearCalculationResults();
                    return;
                }

                // 验证合格数量不能超过检测数量
                if (qualifiedCount > inspectionCount)
                {
                    ClearCalculationResults();
                    return;
                }

                // 验证检测数量必须大于0
                if (inspectionCount <= 0)
                {
                    ClearCalculationResults();
                    return;
                }

                // 计算不合格数量
                int noQualifiedCount = Math.Max(0, inspectionCount - qualifiedCount);

                // 更新不合格数量文本框
                if (textInnoQualified_Count != null)
                {
                    textInnoQualified_Count.Text = noQualifiedCount.ToString();
                }

                // 计算各类缺陷数量总和
                int totalFatal = 0, totalSerious = 0, totalMinor = 0;

                if (dgvIntesting_ItemsId != null && dgvIntesting_ItemsId.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in dgvIntesting_ItemsId.Rows)
                    {
                        // 获取致命缺陷数量
                        if (dgvIntesting_ItemsId.Columns.Contains("colFatalCount") && row.Cells["colFatalCount"].Value != null)
                        {
                            if (int.TryParse(row.Cells["colFatalCount"].Value.ToString(), out int fatal) && fatal >= 0)
                            {
                                totalFatal += fatal;
                            }
                        }

                        // 获取严重缺陷数量
                        if (dgvIntesting_ItemsId.Columns.Contains("colSeriousCount") && row.Cells["colSeriousCount"].Value != null)
                        {
                            if (int.TryParse(row.Cells["colSeriousCount"].Value.ToString(), out int serious) && serious >= 0)
                            {
                                totalSerious += serious;
                            }
                        }

                        // 获取轻微缺陷数量
                        if (dgvIntesting_ItemsId.Columns.Contains("colMinorCount") && row.Cells["colMinorCount"].Value != null)
                        {
                            if (int.TryParse(row.Cells["colMinorCount"].Value.ToString(), out int minor) && minor >= 0)
                            {
                                totalMinor += minor;
                            }
                        }
                    }
                }

                // 计算缺陷率（百分比）
                double fatalRate = inspectionCount > 0 ? (double)totalFatal / inspectionCount * 100 : 0;
                double seriousRate = inspectionCount > 0 ? (double)totalSerious / inspectionCount * 100 : 0;
                double minorRate = inspectionCount > 0 ? (double)totalMinor / inspectionCount * 100 : 0;

                // 更新缺陷率文本框
                if (textInfatal_Defect_Rate != null)
                {
                    textInfatal_Defect_Rate.Text = fatalRate.ToString("F2");
                }
                if (textInserious_Defect_Rate != null)
                {
                    textInserious_Defect_Rate.Text = seriousRate.ToString("F2");
                }
                if (textInminor_Defect_Rate != null)
                {
                    textInminor_Defect_Rate.Text = minorRate.ToString("F2");
                }

                // 根据缺陷率判断检测结果
                string detectionResult = DetermineDetectionResult(fatalRate, seriousRate, minorRate);
                if (textIndetection_Result != null)
                {
                    textIndetection_Result.Text = detectionResult;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"计算过程中出现异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 清空计算结果
        /// </summary>
        private void ClearCalculationResults()
        {
            if (textInnoQualified_Count != null)
            {
                textInnoQualified_Count.Text = "0";
            }
            if (textInfatal_Defect_Rate != null)
            {
                textInfatal_Defect_Rate.Text = "0.00";
            }
            if (textInserious_Defect_Rate != null)
            {
                textInserious_Defect_Rate.Text = "0.00";
            }
            if (textInminor_Defect_Rate != null)
            {
                textInminor_Defect_Rate.Text = "0.00";
            }
            if (textIndetection_Result != null)
            {
                textIndetection_Result.Text = "合格";
            }
        }

        /// <summary>
        /// 清除所有缺陷数量
        /// </summary>
        private void ClearAllDefectCounts()
        {
            if (dgvIntesting_ItemsId != null && dgvIntesting_ItemsId.Rows.Count > 0)
            {
                foreach (DataGridViewRow row in dgvIntesting_ItemsId.Rows)
                {
                    if (dgvIntesting_ItemsId.Columns.Contains("colFatalCount"))
                    {
                        row.Cells["colFatalCount"].Value = 0;
                    }
                    if (dgvIntesting_ItemsId.Columns.Contains("colSeriousCount"))
                    {
                        row.Cells["colSeriousCount"].Value = 0;
                    }
                    if (dgvIntesting_ItemsId.Columns.Contains("colMinorCount"))
                    {
                        row.Cells["colMinorCount"].Value = 0;
                    }
                }
            }
        }

        /// <summary>
        /// 根据缺陷率判断检测结果
        /// </summary>
        private string DetermineDetectionResult(double fatalRate, double seriousRate, double minorRate)
        {
            // 致命缺陷率不能超过5%，严重缺陷率不能超过7%，轻微缺陷率不能超过10%
            if (fatalRate > 5.0 || seriousRate > 7.0 || minorRate > 10.0)
            {
                return "不合格";
            }
            else
            {
                return "合格";
            }
        }

        /// <summary>
        /// 初始化默认值
        /// </summary>
        private void InitializeDefaultValues()
        {
            if (textIndetection_Result != null)
            {
                textIndetection_Result.Text = "合格";
            }
            if (textInfatal_Defect_Rate != null)
            {
                textInfatal_Defect_Rate.Text = "0.00";
            }
            if (textInserious_Defect_Rate != null)
            {
                textInserious_Defect_Rate.Text = "0.00";
            }
            if (textInminor_Defect_Rate != null)
            {
                textInminor_Defect_Rate.Text = "0.00";
            }
            if (textInnoQualified_Count != null)
            {
                textInnoQualified_Count.Text = "0";
            }
        }

        /// <summary>
        /// 初始化日期控件
        /// </summary>
        private void InitializeDateControls()
        {
            if (dateInshipment_Date != null)
            {
                dateInshipment_Date.text = DateTime.Now.ToString("yyyy-MM-dd");
            }
            if (dateIninspection_Date != null)
            {
                dateIninspection_Date.text = DateTime.Now.ToString("yyyy-MM-dd");
            }
        }

        /// <summary>
        /// 加载下拉框数据
        /// </summary>
        private async Task LoadDropdownData()
        {
            try
            {
                // 加载部门下拉框
                var deptResponse = await _apiClient.GetAsync<TestApiResult<List<DepartmentDtos>>>(
                    endpoint: "api/Read/GetDepartment");

                if (deptResponse != null && deptResponse.code == 200)
                {
                    cboaddIndepartment_Id.Items.Clear();
                    cboaddIndepartment_Id.DisplayMember = "departmentName";
                    cboaddIndepartment_Id.ValueMember = "id";
                    cboaddIndepartment_Id.DataSource = deptResponse.data;
                    cboaddIndepartment_Id.SelectedItem = null;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载部门数据失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 验证控件
        /// </summary>
        private void ValidateControls()
        {
            if (textIninspection_Count == null)
            {
                MessageBox.Show("检测数量控件未找到", "初始化错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (textInqualified_Count == null)
            {
                MessageBox.Show("合格数量控件未找到", "初始化错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (textInnoQualified_Count == null)
            {
                MessageBox.Show("不合格数量控件未找到", "初始化错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void btnAddIn_Click(object sender, EventArgs e)
        {
            // 至少需要一条检测项目
            if (dgvIntesting_ItemsId.Rows.Count == 0)
            {
                MessageBox.Show("请先新增检测项目", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (!ValidateQuantityInputs()) return;

            // 解析日期
            if (!DateTime.TryParse(dateInshipment_Date?.text, out var shipmentDate))
            {
                MessageBox.Show("请填写有效的来料日期", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (!DateTime.TryParse(dateIninspection_Date?.text, out var inspectionDate))
            {
                MessageBox.Show("请填写有效的检验日期", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 部门
            int departmentId = 0;
            if (cboaddIndepartment_Id?.SelectedValue != null)
            {
                int.TryParse(cboaddIndepartment_Id.SelectedValue.ToString(), out departmentId);
            }

            // 数量
            int inspectionCount = int.TryParse(textIninspection_Count.Text, out var ic) ? ic : 0;
            int qualifiedCount = int.TryParse(textInqualified_Count.Text, out var qc) ? qc : 0;
            int noQualifiedCount = int.TryParse(textInnoQualified_Count.Text, out var nqc) ? nqc : Math.Max(0, inspectionCount - qualifiedCount);

            // 缺陷率（按已计算结果读取，避免重复计算）
            double fatalRate = double.TryParse(textInfatal_Defect_Rate?.Text, out var fr) ? fr : 0;
            double seriousRate = double.TryParse(textInserious_Defect_Rate?.Text, out var sr) ? sr : 0;
            double minorRate = double.TryParse(textInminor_Defect_Rate?.Text, out var mr) ? mr : 0;

            var items = new List<CreateGoods_InspectionDtos>();
            foreach (DataGridViewRow row in dgvIntesting_ItemsId.Rows)
            {
                if (row?.DataBoundItem is Testing_ItemsDtos item)
                {
                    int fatal = 0, serious = 0, minor = 0;
                    if (dgvIntesting_ItemsId.Columns.Contains("colFatalCount") && row.Cells["colFatalCount"].Value != null)
                        int.TryParse(row.Cells["colFatalCount"].Value.ToString(), out fatal);
                    if (dgvIntesting_ItemsId.Columns.Contains("colSeriousCount") && row.Cells["colSeriousCount"].Value != null)
                        int.TryParse(row.Cells["colSeriousCount"].Value.ToString(), out serious);
                    if (dgvIntesting_ItemsId.Columns.Contains("colMinorCount") && row.Cells["colMinorCount"].Value != null)
                        int.TryParse(row.Cells["colMinorCount"].Value.ToString(), out minor);

                    items.Add(new CreateGoods_InspectionDtos
                    {
                        Inspection_Type = 1,
                        InspectionNode = textIninspectionNode?.Text?.Trim(),
                        InspectionName = textIninspectionName?.Text?.Trim(),
                        Shipment_Date = shipmentDate,
                        Inspection_Date = inspectionDate,
                        Department_Id = departmentId,
                        User_Id = 10038,
                        Sale_Id = null,
                        ProductId = null,
                        Purchase_Id = _selectedPurchaseId,
                        MaterialId = _selectedMaterialId,
                        Batch = textaddInbatch?.Text?.Trim(),
                        Testing_ItemsId = item.Id,
                        Fatal_DefectCount = fatal,
                        Serious_DefectCount = serious,
                        Minor_DefectCount = minor,
                        Inspection_Count = inspectionCount,
                        Qualified_Count = qualifiedCount,
                        NoQualified_Count = noQualifiedCount,
                        Fatal_Defect_Rate = (int)Math.Round(fatalRate),
                        Serious_Defect_Rate = (int)Math.Round(seriousRate),
                        Minor_Defect_Rate = (int)Math.Round(minorRate),
                        Detection_Result = textIndetection_Result?.Text?.Trim(),
                        Notes = textInnotes?.Text?.Trim()
                    });
                }
            }

            if (items.Count == 0)
            {
                MessageBox.Show("请选择至少一条检测项目", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var payload = new { items };
            var resp = await _apiClient.PostAsync<object, TestApiResult<string>>("api/Write/CreateGoods_Inspection", payload);

            if (resp != null && resp.code == 200)
            {
                MessageBox.Show("新增来料检验成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                // 调用回调函数刷新父窗体数据
                _onSuccessCallback?.Invoke();

                this.Close();
            }
            else
            {
                MessageBox.Show($"新增失败：{resp?.msg ?? "接口调用失败"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
